package shouhin;

import DBs.*;
import kessai.CartBeans;
import java.io.IOException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

//受けとった商品ID（itemID）とイコールの商品情報を商品テーブル(SYOUHIN)から抜き出す
public class PutSQL2 extends HttpServlet implements Syori{

	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException{
		this.doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws IOException, ServletException{
		//コンテントのタイプとキャラセット
		res.setContentType("text/html; charset=UTF-8;");
		req.setCharacterEncoding("utf-8");
		//実行文の格納
		String sql = "select * from syouhin";
		//DBExecのインスタンス
		DBExec dbe = new DBExec();
		dbe.selectTable(sql, this, req, res);
	}

	public void syori(ResultSet rs, HttpServletRequest req, HttpServletResponse res){

		try{
			RequestDispatcher dp = null;

			String itemID = req.getParameter("banText");
			String kosuu = req.getParameter("number");

			if ( !itemID.equals("CART") ){//カート見るリンク条件　banText=CART

				if ( kosuu == null || kosuu == "" ){
					req.setAttribute("title", "エラー");
					req.setAttribute("message", "個数が入力されていません！");
					dp = req.getRequestDispatcher("/src/jsp/thanks.jsp");
					dp.forward(req, res);
					return;
				}

				HttpSession session = req.getSession(true);
				ShouhinBeans item = new ShouhinBeans();
				// テスト用カートビーンズ作成
				CartBeans cbean = (CartBeans) session.getAttribute("cart");
				if ( cbean == null ){
					cbean = new CartBeans();
				}

				while( rs.next() ){
					if ( itemID.equals(rs.getString("SYOUHIN_ID")) ){ // 商品IDをキー
						item.setSyouhin_id(rs.getInt("syouhin_id")); // 商品ＩＤの格納
						item.setSyouhinmei(rs.getString("syouhinmei")); // 商品名
						item.setNedan(rs.getInt("nedan")); // 値段
						item.setSetumei(rs.getString("setumei")); // 説明
						item.setImg_url(rs.getString("Img_url")); // イメージＵＲＬ
						item.setKosuu(Integer.parseInt(kosuu));
						cbean.addItem(item);
						session.setAttribute("cart", cbean);
						break;
					}
				}
			}

			dp = req.getRequestDispatcher("../src/jsp/kessai/cart.jsp");
			dp.forward(req, res);

		}catch (IOException e) {
			e.printStackTrace();
		}catch (ServletException e) {
			e.printStackTrace();
		}catch(SQLException e){
			e.printStackTrace();
		}
	}


}
